package ru.spb.osll.myfit.client.widget;

import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.TextBox;

public class FixedTableWidget extends TableWidget {

  private int m_columnCount = 0;

  public FixedTableWidget(GWTWidgetFactory gwtWidgetFactory,Table table) {
    super(gwtWidgetFactory, table);

    if (table.getData().size() > 1)
      m_columnCount = table.getData().elementAt(1).size();
    m_deleteCellItem.setVisible(false);
    m_addCellItem.setVisible(false);
  }


  protected void addNewRow(int row) {
    if (row > 1) {
      m_flexTable.insertRow(row);
      for (int j = 0; j < m_columnCount; ++j) {
        TextBox tb = createTextEdit(new TableCell());
        tb.setReadOnly(false);
        m_flexTable.setWidget(row, j, tb);
      }
    }
  }

  @Override
  protected void addNewCell(int row, int cell) {
    // not applicable
  }

  @Override
  protected void deleteCell(int row, int cell) {
    // not applicable
  }

  protected void setReadOnly(boolean isReadOnly) {
    int rowCount = m_flexTable.getRowCount();
    for (int i = 0; i < rowCount; i++) {
      int cellCount = m_flexTable.getCellCount(i);
      for (int j = 0; j < cellCount; ++j) {
        try {
          TextBox tb =((TextBox) m_flexTable.getWidget(i, j));     
          tb.setReadOnly(isReadOnly ||
              (i < 2));
        } catch (Exception ex) {
        }
      }
    }    
  }
  
  public void removeRow(int row) {
    if (row >= 2) {
      m_flexTable.removeRow(row);
    }
  }

  protected void refreshTable(FlexTable table) {
  }

  protected void tuneMenu() {
    m_addRowItem.setVisible(m_selectedRow >= 1);
    m_deleteRowItem.setVisible(m_selectedRow >= 2 &&
        m_flexTable.getRowCount() > 1);
  }

  @Override
  protected void setSpecifiedStyles(int row, int cell) {
    if (row <= 1) {
      m_flexTable.getCellFormatter().addStyleName(row, cell, IStyleConstants.TABLE_CELL_HEADER_STYLE_NAME);
    } 
  }
}
